package cashback

import (
	"time"
)

// UserCashback 用户返现信息结构体
type UserCashback struct {
	UserID          uint                   // 用户ID
	TotalAmount     float64                // 总金额
	Rates           CashbackRates          // 返现比例配置
	RecordManager   *CashbackRecordManager // 返现记录管理器
	InstallmentInfo struct {               // 分期信息
		MonthlyFee  float64   // 月费
		TotalMonths int       // 总月数
		HasRenewal  bool      // 是否续约3年
		CurrentYear int       // 当前所处年份(1-5)
		OrderDate   time.Time // 订单时间
	}
}

// NewUserCashback 创建新的用户返现实例
func NewUserCashback(userID uint) *UserCashback {
	return &UserCashback{
		UserID:        userID,
		Rates:         DefaultRates,
		RecordManager: NewCashbackRecordManager(),
		InstallmentInfo: struct {
			MonthlyFee  float64
			TotalMonths int
			HasRenewal  bool
			CurrentYear int
			OrderDate   time.Time
		}{
			OrderDate: time.Now(),
		},
	}
}

// CalculateAndRecordBenefit 计算并记录返现
func (u *UserCashback) CalculateAndRecordBenefit() float64 {
	// 计算分享返现
	shareCashback := CalculateShareCashback(u.TotalAmount, u.Rates)
	if shareCashback > 0 {
		u.RecordManager.AddShareCashbackRecord(u.UserID, u.TotalAmount, shareCashback)
	}

	// 计算年费
	annualFee := u.InstallmentInfo.MonthlyFee * 12

	// 计算分期返现
	installmentCashback := CalculateInstallmentCashback(
		u.InstallmentInfo.CurrentYear,
		annualFee,
		u.InstallmentInfo.HasRenewal,
		u.Rates,
		u.InstallmentInfo.OrderDate,
	)

	// 计算每日返现
	dailyCashback := CalculateDailyCashback(installmentCashback, u.InstallmentInfo.OrderDate)

	if dailyCashback > 0 {
		u.RecordManager.AddInstallmentCashbackRecord(
			u.UserID,
			u.InstallmentInfo.CurrentYear,
			u.InstallmentInfo.MonthlyFee,
			dailyCashback,
		)
	}

	return shareCashback + dailyCashback
}

// CalculateShareCashback 计算分享返现
func (u *UserCashback) CalculateShareCashback() float64 {
	shareCashback := CalculateShareCashback(u.TotalAmount, u.Rates)
	if shareCashback > 0 {
		u.RecordManager.AddShareCashbackRecord(u.UserID, u.TotalAmount, shareCashback)
	}
	return shareCashback
}

// CalculateInstallmentCashback 计算分期返现
func (u *UserCashback) CalculateInstallmentCashback() float64 {
	annualFee := u.InstallmentInfo.MonthlyFee * 12
	installmentCashback := CalculateInstallmentCashback(
		u.InstallmentInfo.CurrentYear,
		annualFee,
		u.InstallmentInfo.HasRenewal,
		u.Rates,
		u.InstallmentInfo.OrderDate,
	)

	if installmentCashback > 0 {
		u.RecordManager.AddInstallmentCashbackRecord(
			u.UserID,
			u.InstallmentInfo.CurrentYear,
			u.InstallmentInfo.MonthlyFee,
			installmentCashback,
		)
	}
	return installmentCashback
}
